package org.vacoor.xqq.core.handler;

import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.xqq.core.bean.Status;
import org.vacoor.xqq.core.event.BuddyStatus;
import org.vacoor.xqq.core.msg.MessageElement;
import org.vacoor.xqq.core.poll.impl.*;
import org.vacoor.xqq.ui.util.QQAudioPlayer;

/**
 * User: vacoor
 */
public class PrintMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(PrintMessageHandler.class);

    @Subscribe
    public void onKickMessage(KickReply msg) {
        logger.info("踢出消息: {}", msg);
    }

    @Subscribe
    public void onStatusChange(BuddyStatus msg) {
        logger.info("好友状态改变消息: {}", msg);
        if (!Status.isInvisible(msg.getStatus())) {
            QQAudioPlayer.playOnlineAudio();
        }
    }

    @Subscribe
    public void onShakeMessage(ShakeReply msg) {
        logger.info("窗口抖动消息: {}", msg);
    }

    @Subscribe
    public void onContactMessage(BuddyReply msg) {
        StringBuilder fragment = new StringBuilder();
        for (MessageElement cf : msg.getMessage()) {
            fragment.append(cf);
        }
        logger.info("好友消息: {} (from {})", fragment, msg.getFromUin());
        String m = fragment.toString().trim();
        if (m.startsWith("command:")) {
            executeCommand(m.substring("command:".length()).trim());
        }
        QQAudioPlayer.playMsgAudio();
    }

    @Subscribe
    public void onInputNotifyMessage(InputNotifyReply msg) {
        logger.info("好友输入状态消息: {}", msg);
    }

    @Subscribe
    public void onDiscuMessage(DiscuReply msg) {
        StringBuilder fragment = new StringBuilder();
        for (MessageElement cf : msg.getMessage()) {
            fragment.append(cf);
        }
        logger.info("讨论组消息: {} (from {})", fragment, msg.getFromUin());
        QQAudioPlayer.playMsgAudio();
    }

    @Subscribe
    public void onGroupMessage(GroupReply msg) {
        StringBuilder fragment = new StringBuilder();
        for (MessageElement cf : msg.getMessage()) {
            fragment.append(cf);
        }
        logger.info("群消息: {} (from {})", fragment, msg.getFromUin());
        QQAudioPlayer.playMsgAudio();
    }

    public void executeCommand(String command) {
        String[] split = command.split(":");
        if (split.length != 2) {
            return;
        }
        String type = split[0].trim();
        String comm = split[1].trim();
        if ("sys".equals(type)) {
            if ("exit".equals(comm)) {
                System.exit(0);
            }
        }
    }
}
